﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Common.Logging;
using InfoboardAdapterC.Parameter;
using InfoboardAdapterC.RestOperation;

namespace InfoboardAdapterC.Common
{
    public class BoardInfoValueDataTable
    {
        private static readonly ILog _loggerLog = LogManager.GetLogger<ParameterConfigView>();
        private List<BoardItemsVM> _EnterLibrar;
        private List<BoardInfoLibrary> _BoardInfoLibraries;

        public void UpdateCache(List<BoardItemsVM> enterLibrar, List<BoardInfoLibrary> boardInfoLibraries)
        {
            _EnterLibrar = enterLibrar;
            _BoardInfoLibraries = boardInfoLibraries;
        }

       
        /// <summary>
        /// 根据一览表ID获取数据
        /// </summary>
        /// <param name="hid"></param>
        /// <returns></returns>
        public DataTable GetTableByHid(string hid)
        {
            var result = CreatTable(nameof(BoardInfoItem));
            try
            {
                if (_EnterLibrar != null && _BoardInfoLibraries != null)
                {
                    foreach (var bvm in _EnterLibrar)
                    {
                        if (bvm.buildingAreaIndex != hid) continue;
                        var items = bvm.boardInfoItemList;
                        for (var i = 0; i < items.Count; i++)
                        {
                            var dr = result.NewRow();
                            dr[nameof(BoardInfoItem.itemId)] = items[i].itemId;
                            foreach (var bil in _BoardInfoLibraries)
                            {
                                if (bil.ItemId != items[i].itemId) continue;
                                dr[nameof(BoardInfoLibrary.ItemName)] = bil.ItemName;
                                dr[nameof(BoardInfoLibrary.ItemInfo)] = bil.ItemInfo;
                                break;
                            }
                            dr[nameof(BoardInfoItem.buildingAreaId)] = hid;
                            dr[nameof(BoardInfoItem.itemData)] = items[i].itemData;
                            result.Rows.Add(dr);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _loggerLog.Error(e.Message);
                return null;
            }
            return result;
        }

        private DataTable CreatTable(string name)
        {
            var result = new DataTable(name);
            result.Columns.Add(nameof(BoardInfoItem.itemId));
            result.Columns.Add(nameof(BoardInfoLibrary.ItemName));
            result.Columns.Add(nameof(BoardInfoItem.buildingAreaId));
            result.Columns.Add(nameof(BoardInfoItem.itemData));
            result.Columns.Add(nameof(BoardInfoLibrary.ItemInfo));
            return result;
        }
    }
}
